13. Arrays

Arrays

ND079 C1 L0 A13 Arrays

An** array** is a fixed-sized data structure that is used to store multiple values—such as a series of phone numbers, as we saw in the video.

Creating an Array

Here's an example of some code that creates an array of size four, containing four integer values:

int [] numbers  = {1, 2, 3, 4};

Notice that creating an array involves three steps:

  1. Declare the type of the array, using brackets (as in int []).
  2. Name the array (in this example, the name is numbers).
  3. Add values to the array.

In this example, we are using an array literal to add the values, which simply means we are placing the values in a comma-separated list inside some curly braces, {1, 2, 3, 4}.

Accessing Array Elements

We can access the elements in an array based on their numerical index. Let's revisit the above example:

int [] numbers  = {1, 2, 3, 4};

To access one of the numbers, we would type the name of the array, followed by brackets containing the index number of the item we want—as in numbers[1].

Note that arrays start with an index of 0, not 1 (this is called zero-based indexing and is common in programming). So if we wanted to print the first item in the array, we would type:

System.out.printLn(numbers[0]);

Given an array int [] numbers = {1, 2, 3, 4};. Select the correct statement for assigning the value 3 in the array to a variable.

SOLUTION: ```int variable = numbers[2];```

Another Way to Create an Array

Here's another way we can create an array and add values to it:

int [] numbers = new int[4];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;

This approach uses the new keyword to create a new array object of size 4, and then we assign values to the four spaces created in the array. This style will feel more normal to you after we have worked with classes and objects later in the course.